import { Injectable } from '@nestjs/common';
import { PrismaService } from 'src/prisma/prisma.service';
import { UserDto } from './dto/create-user.dto';
import { resultUtil } from 'src/utils/result';
import * as dayjs from 'dayjs';

@Injectable()
export class UserService {
  constructor(private readonly prismaService: PrismaService) {}

  /**
   * 查询用户列表
   */
  async query(queryInfo) {
    const { username, nickname, currentPage, pageSize } = queryInfo;
    const skip = (currentPage - 1) * pageSize;

    const where = {} as any;
    if (username) {
      where.username = { contains: username };
    }
    if (nickname) {
      where.nickname = { contains: nickname };
    }

    const [records, total] = await Promise.all([
      this.prismaService.user.findMany({
        where,
        skip,
        take: pageSize,
        select: {
          id: true,
          username: true,
          nickname: true,
          createdAt: true,
          img: true,
          password: false,
          // atricles: true,
          role: true
        },
      }),
      this.prismaService.user.count({ where }),
    ]);
    return resultUtil('', '000000', {
      records: records?.map((item) => {
        let result = {
          ...item,
          disabeld: item.role =='admin', // 管理员不能删除
          role: item.role == 'admin' ? '管理员' : '用户',
          createdAt: dayjs(new Date(item.createdAt)).format(
            'YYYY-MM-DD HH:mm:ss',
          ),
        };
        // delete result.atricles
        return result
      }) || [],
      total: total,
    });
  }

  /**
   * 删除用户
   */
  async delete(id: number) {
    const res = await this.prismaService.article.findMany({
      where: {authorId: id}
    })
    if (res.length) {
      return resultUtil('当前用户有文章无法删除用户', '000001')
    }
    await this.prismaService.user.delete({
      where: { id: +id },
    });
    return resultUtil('', '000000');
  }

  /**
   * 更新用户
   */
  async update(userDto: UserDto) {
    delete(userDto.articlesAccount)
    await this.prismaService.user.update({
      where: { id: +userDto.id },
      data: {
        ...userDto
      },
    });
    return resultUtil('', '000000');
  }

  /**
   * 查询个人信息
  */
  async userInfo(id: number) {
    const res= await this.prismaService.user.findUnique({
      where: { id },
      select: {
        id: true,
        username: true,
        nickname: true,
        img: true,
        gitee: true,
        giteeurl: true,
        github: true,
        githuburl: true,
        zh: true,
        zhurl: true,
        csdn: true,
        csdnurl: true,
        atricles: true,
      }
    })
    const result = {
      ...res,
      articlesAccount: res.atricles.length
    }
    delete result.atricles
    return resultUtil('', '000000', {...result});
  }

  /**
   * 获取个人文章列表
  */
  async privateArticle(authorId: number) {
    const res = await this.prismaService.article.findMany({
      where: { authorId }
    })
    let result = res?.map(item => {
      return {
        ...item,
        createdAt: dayjs(new Date(item.createdAt)).format('YYYY-MM-DD HH:mm:ss')
      }
    }) || []
    return resultUtil('', '000000', [...result])
  }
}
